package grpc

import (
	"context"
	"gitee.com/kmyss/gf-ex/ysgrpc"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/gf-ex/ysutils"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gproc"
	"os"
)

func init() {
	service.RegisterGrpc(&sGrpc{})
}

type sGrpc struct {
	l *glog.Logger // 日志
}

func (s *sGrpc) log() *glog.Logger {
	if s.l == nil {
		s.l = yslog.Log("logic.grpc")
	}
	return s.l
}

func (s *sGrpc) Run(ctx context.Context, config *model.GRPCCfgInput) error {
	ss := ysgrpc.NewServer(ctx)

	if config.RunMQ {
		ss.AddRegistrarHandler(ysgrpc.RegisterMqServer)
	}
	gproc.AddSigHandlerShutdown(func(sig os.Signal) {
		ss.Stop()
	})
	ysutils.ProcInstanceListen()
	s.log().Info(ctx, "输入 Ctrl+C 停止服务")

	err := ss.Run()
	if err != nil {
		return err
	}

	s.log().Info(ctx, "停止 GRPC Server")
	return nil
}
